<template>
  <nut-popup 
    v-model:visible="visible" 
    position="bottom" 
    :style="{ height: '70vh' }"
    round
    closeable
    @close="handleClose"
  >
    <view class="h-full flex flex-col">
      <!-- 头部 -->
      <view class="flex items-center justify-between p-[30rpx] border-b border-[#f0f0f0]">
        <text class="text-[32rpx] font-bold text-[#333]">选择个人从业者</text>
        <view class="flex items-center gap-[20rpx] mr-[90rpx]">
          <text class="text-[24rpx] text-[#666]">已选 {{ internalSelectedItems.length }} 项</text>
          <nut-button 
            type="primary" 
            size="small"
            @click="handleConfirm"
          >
            确认选择
          </nut-button>
        </view>
      </view>

      <!-- 搜索框 -->
      <view class="p-[30rpx] border-b border-[#f0f0f0]">
        <nut-searchbar
          v-model="searchKeyword" 
          placeholder="搜索个人从业者姓名"
          @search="handleSearch"
          @clear="handleClear"
        />
      </view>

      <!-- 列表内容 -->
      <view class="flex-1 overflow-y-auto">
        <template v-if="filteredList.length > 0">
          <view 
            v-for="item in filteredList" 
            :key="item.id"
            class="flex items-center p-[30rpx] border-b border-[#f0f0f0] last:border-b-0"
          >
            <nut-checkbox 
              :model-value="internalSelectedItems.includes(item.id)" 
              @update:model-value="(val) => handleItemCheck(val, item.id)"
              class="mr-[20rpx] !text-[#165DFF]"
            />
            <view class="flex-1 min-w-0" @tap="viewPersonDetail(item.id)">
              <text class="text-[28rpx] font-medium text-[#333] block mb-[8rpx]">{{ item.name }}</text>
              <view class="flex items-center gap-[20rpx]">
                <view class="text-[22rpx] text-[#999] w-full truncate">{{ item.brief_introduction || '暂无简介' }}</view>
                <!-- <text class="text-[22rpx] text-[#999]">经验: {{ item.experience || '暂无' }}</text> -->
              </view>
            </view>
          </view>
        </template>
        
        <!-- 空数据提示 -->
        <template v-else>
          <view class="flex flex-col items-center justify-center h-[400rpx]">
            <nut-empty description="暂无个人从业者数据" />
          </view>
        </template>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore && !loading" class="p-[30rpx] text-center">
        <nut-button 
          type="default" 
          size="small"
          class="w-full"
          @click="loadMore"
        >
          加载更多
        </nut-button>
      </view>

      <!-- 加载中 -->
      <view v-if="loading" class="p-[30rpx] text-center">
        <text class="text-[24rpx] text-[#666] ml-[10rpx]">加载中...</text>
      </view>
    </view>
  </nut-popup>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { post } from '../utils/request';
import Taro from '@tarojs/taro';

/**
 * 组件属性
 */
interface Props {
  modelValue: boolean;
  selectedItems: number[];
}

/**
 * 组件事件
 */
interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'confirm', items: any[]): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  selectedItems: () => []
});

const emit = defineEmits<Emits>();

/**
 * 弹窗显示状态
 */
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});

/**
 * 搜索关键词
 */
const searchKeyword = ref('');

/**
 * 当前页码
 */
const currentPage = ref(1);

/**
 * 每页数量
 */
const pageSize = ref(20);

/**
 * 是否还有更多数据
 */
const hasMore = ref(true);

/**
 * 加载状态
 */
const loading = ref(false);

/**
 * 个人从业者列表数据
 */
const personList = ref<any[]>([]);

/**
 * 内部选择状态管理
 */
const internalSelectedItems = ref<number[]>([]);

/**
 * 过滤后的列表
 */
const filteredList = computed(() => {
  if (!searchKeyword.value) {
    return personList.value;
  }
  return personList.value.filter(item => 
    item.real_name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    (item.skills && item.skills.toLowerCase().includes(searchKeyword.value.toLowerCase()))
  );
});

/**
 * 监听弹窗显示状态
 */
watch(visible, (newVal) => {
  if (newVal) {
    // 初始化内部选择状态为父组件传入的选择状态
    internalSelectedItems.value = [...props.selectedItems];
    console.log('PersonSelectorModal 打开，初始化选择状态:', internalSelectedItems.value);
    loadPersonList();
  }
});

// 监听 selectedItems 变化
watch(() => props.selectedItems, (newVal) => {
  console.log('PersonSelectorModal selectedItems 变化:', newVal);
  if (visible.value) {
    internalSelectedItems.value = [...newVal];
  }
}, { deep: true });

/**
 * 加载个人从业者列表
 */
const loadPersonList = async (page = 1, isLoadMore = false) => {
  if (loading.value) return;
  
  loading.value = true;
  
  try {
    const res = await post('/dictionary/personal', {
      pageNo: page,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    });
    
    if (res.code === 0) {
      const newData = res.data.map((item: any) => ({
        ...item.columns,
      }));
      
      if (isLoadMore) {
        personList.value = [...personList.value, ...newData];
      } else {
        personList.value = newData;
      }
      
      hasMore.value = newData.length === pageSize.value;
      currentPage.value = page;
    } else {
      Taro.showToast({
        title: res.message || '加载失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('加载个人从业者列表失败:', error);
    Taro.showToast({
      title: '网络错误',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

/**
 * 加载更多数据
 */
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    loadPersonList(currentPage.value + 1, true);
  }
};

/**
 * 搜索处理
 */
const handleSearch = () => {
  currentPage.value = 1;
  hasMore.value = true;
  loadPersonList(1, false);
};

/**
 * 清空搜索
 */
const handleClear = () => {
  searchKeyword.value = '';
  currentPage.value = 1;
  hasMore.value = true;
  loadPersonList(1, false);
};

/**
 * 选择/取消选择项目
 */
const handleItemCheck = (checked: boolean, itemId: number) => {
  const idx = internalSelectedItems.value.indexOf(itemId);
  if (checked && idx === -1) {
    internalSelectedItems.value.push(itemId);
  } else if (!checked && idx > -1) {
    internalSelectedItems.value.splice(idx, 1);
  }
  console.log('选择状态变更:', checked, itemId, internalSelectedItems.value);
};

/**
 * 查看个人从业者详情
 */
const viewPersonDetail = (personId: number) => {
  Taro.navigateTo({
    url: `/pages/mine/other?id=${personId}`
  });
};

/**
 * 确认选择
 */
const handleConfirm = () => {
  const selectedPersons = personList.value.filter(item => 
    internalSelectedItems.value.includes(item.id)
  );
  
  emit('confirm', selectedPersons);
  handleClose();
};

/**
 * 关闭弹窗
 */
const handleClose = () => {
  visible.value = false;
  // 重置搜索状态
  searchKeyword.value = '';
  currentPage.value = 1;
  hasMore.value = true;
  // 不重置内部选择状态，保持选择状态
};
</script>
